package com.pzsh.handler;

import com.pzsh.enums.CodeBaseEnum;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.math.NumberUtils;

import java.io.IOException;

/**
 * 接口返回枚举类型时序列化用
 */
public class EnumJsonSerializer extends JsonSerializer<CodeBaseEnum> {
    @Override
    public void serialize(CodeBaseEnum anEnum, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (null == anEnum) {
            return;
        }

        int code = NumberUtils.toInt(EnumTools.getInvokeValue(anEnum, "code"));
        if (code == -1) {
            code = anEnum.code();
        }
        String msg = EnumTools.getInvokeValue(anEnum, "msg");
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("msg", msg);
        jsonGenerator.writeObject(json);
    }
}
